package com.fei.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fei.yygh.cmn.listener.DictListener;
import com.fei.yygh.cmn.mapper.DitMapper;
import com.fei.yygh.cmn.service.DitService;
import com.fei.yygh.model.cmn.Dict;
import com.fei.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DitServiceImpl extends ServiceImpl<DitMapper, Dict> implements DitService {

//    private final DitMapper ditMapper;
//
//    public DitServiceImpl(DitMapper ditMapper) {
//        this.ditMapper = ditMapper;
//    }

    @Autowired
    private DitMapper ditMapper;

//    private final DitService ditService;
//
//    public DitServiceImpl(DitService ditService) {
//        this.ditService = ditService;
//    }

    //判断数据下面是否存在子数据
    private boolean isSon(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);

        Long count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * longfei
     * 根据ID查询子数据
     *  @Cacheable缓存注解，将list存入dict缓存中，规则是keyGenerator
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findSonData(Long id) {
        //条件构造器，用于查询SQL语句的条件构造
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);

        //baseMapper是ServiceImpl中已经注入了慈湖可以直接用
        List<Dict> list = baseMapper.selectList(queryWrapper);
        //向每个dict对象中的hasChildren属性添加值
        for (Dict dict : list){
            Long dictId = dict.getId();
            dict.setHasChildren(this.isSon(dictId));
        }
        return list;
    }

    /**
     * longfei
     * 导出字典数据
     * @param response
     */
    @Override
    public void exportExcelData(HttpServletResponse response) {
        //设置下载信息
        /**
         *：URLEncoder.encode() 方法会抛出 UnsupportedEncodingException，必须进行异常处理
         * URLEncoder.encode可以防止中文乱码
         *Content-disposition ：头信息，表示让该操作以下载的方式打开
         */
        try{
            //1.设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //文件名字
            String fileName = URLEncoder.encode("数据字典",StandardCharsets.UTF_8.name());
            response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");

            //2.从数据库进行查询并下载数据
            List<Dict> list = baseMapper.selectList(null);
            //将list Dict数据转换为DictEeVo
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for (Dict dict : list){
                DictEeVo dictEeVo = new DictEeVo();
//                dictEeVo.setId(dict.getId());
//                dictEeVo.setParentId(dict.getParentId());
//                dictEeVo.setValue(dict.getValue());
//                dictEeVo.setDictCode(dict.getDictCode());
//                dictEeVoList.add(dictEeVo);
                //上面是传统方法，下面是采用对象的克隆方法
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVoList.add(dictEeVo);
            }

            //调用方法将数据写入excel中
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictEeVoList);

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * longfei
     * 导入excel数据
     * CacheEvict 数据更新后会清理缓存并重新加载
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importExcel( MultipartFile file) {
        try(InputStream inputStream = file.getInputStream()) {
//          这个方法不行，无法定位到Listener导致导入失败
//          EasyExcel.read(file.getInputStream(), DictEeVo.class,new DictListener(ditMapper)).sheet("dict").doRead();

            // 关键修改：明确绑定监听器并指定Sheet
            ExcelReader excelReader = EasyExcel.read(
                    inputStream,
                    DictEeVo.class,
                    new DictListener(ditMapper)  // 手动传入Mapper
            ).build();

            // 读取第一个Sheet（索引从0开始）
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getNameByValue(Long value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("value",value);
        Dict dict = baseMapper.selectOne(wrapper);
        if (dict!=null){
            return dict.getName();
        }
        return null;
    }

    @Override
    public String getNameByDictCode(String dictCode, Long value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<Dict>();
        wrapper.eq("dict_code",dictCode);
        Dict dict1 = baseMapper.selectOne(wrapper);

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>();
        queryWrapper.eq("parent_id",dict1.getId());
        queryWrapper.eq("value",value);
        Dict dict2 = baseMapper.selectOne(queryWrapper);
        return dict2.getName();
    }


}
